//
//  CGFloat+ZLExtensions.swift
//  ZLKit_SwiftDemo_Example
//
//  Created by itzhaolei on 2022/1/17.
//  Copyright © 2022 CocoaPods. All rights reserved.
//


public extension UIView {
    
    
    /// 起点 x
    var x: CGFloat {
        get {
            return frame.origin.x
        }
        set {
            frame = CGRect(x: newValue, y: y, width: width, height: height)
        }
    }
    
    /// 起点 y
    var y: CGFloat {
        get {
            return frame.origin.y
        }
        set {
            frame = CGRect(x: x, y: newValue, width: width, height: height)
        }
    }
    
    /// 宽
    var width: CGFloat {
        get {
            return frame.size.width
        }
        set {
            frame = CGRect(x: x, y: y, width: newValue, height: height)
        }
    }
    
    /// 高
    var height: CGFloat {
        get {
            return frame.size.height
        }
        set {
            frame = CGRect(x: x, y: y, width: width, height: newValue)
        }
    }
    
    /// 最大 x
    var maxX: CGFloat {
        get {
            return x + width
        }
        set {
            x = newValue - width
        }
    }
    
    /// 最大 y
    var maxY: CGFloat {
        get {
            return y + height
        }
        set {
            y = newValue - height
        }
    }
    
    /// 中心 x
    var midX: CGFloat {
        get {
            return x + width / 2
        }
        set {
            x = newValue - width / 2
        }
    }
    
    /// 中心 y
    var midY: CGFloat {
        get {
            return y + height / 2
        }
        set {
            y = newValue - height / 2
        }
    }
    
    
}


public extension UIView {
    
    /// 阴影
    ///
    /// 尽量使用干净的UIView来做背景，其他子类可能会出现圆角显示失败的情况
    ///
    func shadow(background: UIColor = .white, cornerRadius: CGFloat = 10, color: UIColor = .lightGray, offset: CGSize = .init(width: 2, height: 2), radius: CGFloat = 4.0, opacity: Float = 0.7) {
        backgroundColor = background
        layer.cornerRadius = cornerRadius
        layer.shadowColor = color.cgColor
        layer.shadowOffset = offset
        layer.shadowRadius = radius
        layer.shadowOpacity = opacity
    }
    
}

public extension UIView {
    
    /// 使其成为移动对象
    ///
    /// 尽量使用干净的UIView来调用
    ///
    /// 支持承载子视图，但子视图不能有点击事件，可通过参数去识别点击的子视图对象
    ///
    func move(inset: UIEdgeInsets = .zero, action: Params_one_void<UITapGestureRecognizer>) {
        AssociatedKey.action.moveTap = action
        AssociatedKey.action.contentInset = inset
        AssociatedKey.forbidUse = true
        isUserInteractionEnabled = true
        let tapGr = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
        addGestureRecognizer(tapGr)
        let panGr = UIPanGestureRecognizer(target: self, action: #selector(panAction(_:)))
        addGestureRecognizer(panGr)
        tapGr.require(toFail: panGr)
    }
    
    /// 关闭所有的子视图交互
    func closeSubviewsUserInteractionEnabled() {
        for view in subviews {
            view.isUserInteractionEnabled = false
        }
    }
    
    @objc private func tapAction(_ tap: UITapGestureRecognizer) {
        AssociatedKey.action.moveTap?(tap)
    }
    
    @objc private func panAction(_ pan: UIPanGestureRecognizer) {
        let point = pan.translation(in: self.superview)
        if (pan.state == .began) {
            AssociatedKey.action.originalOrigin = .init(x: frame.origin.x, y: frame.origin.y)
        }else if (pan.state == .changed) {
            var x = AssociatedKey.action.originalOrigin.x + point.x
            var y = AssociatedKey.action.originalOrigin.y + point.y
            if x > (superview?.frame.width ?? 0) - frame.width - AssociatedKey.action.contentInset.right || x < 0 + AssociatedKey.action.contentInset.left {
                if x < 0 + AssociatedKey.action.contentInset.left {
                    x = 0 + AssociatedKey.action.contentInset.left
                }else {
                    x = (superview?.frame.width ?? 0) - frame.width - AssociatedKey.action.contentInset.right
                }
            }
            if y > (superview?.frame.height ?? 0) - frame.height - AssociatedKey.action.contentInset.bottom || y < 0 + AssociatedKey.action.contentInset.top {
                if y < 0 + AssociatedKey.action.contentInset.top {
                    y = 0 + AssociatedKey.action.contentInset.top
                }else {
                    y = (superview?.frame.height ?? 0) - frame.height - AssociatedKey.action.contentInset.bottom
                }
            }
            frame = .init(x: x, y: y, width: frame.width, height: frame.height)
        }else if (pan.state == .ended) {
            UIView.animate(withDuration: 0.25) {[weak self] in
                guard let self = self else { return }
                var x = self.frame.origin.x
                if x + self.frame.width / 2.0 > (self.superview?.frame.width ?? 0) / 2 {
                    x = (self.superview?.frame.width ?? 0) - self.frame.width - AssociatedKey.action.contentInset.right
                }else {
                    x = 0 + AssociatedKey.action.contentInset.left
                }
                self.frame = .init(x: x, y: self.frame.origin.y, width: self.frame.width, height: self.frame.height)
            } completion: {[weak self] _ in
                AssociatedKey.action.originalOrigin = self?.frame.origin ?? .init()
            }
        }
    }
        
}


// 追加点击事件
public extension UIView {
    
    struct Action {
        public var tap: Params_one_void<UIView> = nil
        fileprivate var originalOrigin: CGPoint = .zero
        fileprivate var contentInset: UIEdgeInsets = .zero
        fileprivate var moveTap: Params_one_void<UITapGestureRecognizer> = nil
    }
    
    struct AssociatedKey {
        static var action: Action = .init()
        static var forbidUse: Bool = false
    }
    
    var action: Action {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.action) as? Action ?? .init()
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.action, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            guard action.tap != nil, !AssociatedKey.forbidUse else {
                if AssociatedKey.forbidUse && action.tap != nil {
                    print("⚠️ 当前action.tap无法被响应，因为该视图已经调用了move函数，点击事件将从move内进行派发")
                }
                return
            }
            isUserInteractionEnabled = true
            addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGrAction)))
        }
    }
    
    @objc func tapGrAction() {
        action.tap?(self)
    }
    
}
